/* JavaLog - package tracker 
 * 
 * Copyright (C) 2009  Allyson Lima, Diego Pedro, Victor Freire
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software 
 * Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this 
 * program.  If not, see <http://www.gnu.org/licenses/>.
 */
package br.edu.ufcg.ccc.javalog.view;

import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.util.Arrays;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

import br.edu.ufcg.ccc.javalog.controller.FranchiseController;
import br.edu.ufcg.ccc.javalog.event.FranchiseEvent;
import br.edu.ufcg.ccc.javalog.exceptions.FranchiseControllerException;
import br.edu.ufcg.ccc.javalog.listener.FranchiseListener;
import br.edu.ufcg.ccc.javalog.model.Data;
import br.edu.ufcg.ccc.javalog.model.Franchise;
import br.edu.ufcg.ccc.javalog.model.Validator;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
/** 
 * View for managing a franchise nearest Franchises.
 * @author Allyson Lima, Diego Pedro, Victor Freire
 * @version 22/11/09 
 */
@SuppressWarnings("serial")
public class NearestFranchisesView extends AbstractView implements FranchiseListener {
	private FranchiseController franchiseController;
	private Franchise franchise;
	private JButton buttonBack;
	private AbstractAction abstractAction1;
	private AbstractAction actionDelete;
	private AbstractAction actionAdd;
	private JList listNearestFranchises;
	private JScrollPane scrollListNearestFranchises;
	private JButton buttonAdd;
	private JButton buttonDelete;
	private JLabel labelFranchiseName;

	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				NearestFranchisesView inst = new NearestFranchisesView();
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}
	
	private NearestFranchisesView() {
		super();
		initGUI();
	}
	
	/**
	 * Creates this view for the specified franchise model object.
	 * @param franchise the model to view
	 */
	public NearestFranchisesView(Franchise franchise) {
		this();
		Validator.validateObject(franchise, new IllegalArgumentException("null franchise received"));
		this.franchise = franchise;
		this.franchiseController = new FranchiseController(franchise);
		this.franchise.addFranchiseListener(this);
		refreshView();
	}
	
	private void initGUI() {
		try {
			GroupLayout thisLayout = new GroupLayout((JComponent)getContentPane());
			getContentPane().setLayout(thisLayout);
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			this.setTitle("Franquias conectadas");
			{
				labelFranchiseName = new JLabel();
				labelFranchiseName.setText("Nome da Franquia");
			}
			{
				buttonBack = new JButton();
				buttonBack.setText("Voltar");
				buttonBack.setAction(getAbstractAction1());
			}
			{
				buttonDelete = new JButton();
				buttonDelete.setText("Remover conexão");
				buttonDelete.setAction(getActionDelete());
			}
			thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
				.addContainerGap()
				.addComponent(labelFranchiseName, GroupLayout.PREFERRED_SIZE, 14, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
				.addComponent(getScrollListNearestFranchises(), 0, 246, Short.MAX_VALUE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				.addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				    .addComponent(buttonBack, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				    .addComponent(buttonDelete, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				    .addComponent(getButtonAdd(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
				.addContainerGap());
			thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(thisLayout.createParallelGroup()
				    .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				        .addComponent(getButtonAdd(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				        .addComponent(buttonDelete, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				        .addGap(0, 220, Short.MAX_VALUE)
				        .addComponent(buttonBack, GroupLayout.PREFERRED_SIZE, 82, GroupLayout.PREFERRED_SIZE)
				        .addGap(8))
				    .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				        .addComponent(labelFranchiseName, GroupLayout.PREFERRED_SIZE, 510, GroupLayout.PREFERRED_SIZE)
				        .addGap(0, 8, Short.MAX_VALUE))
				    .addComponent(getScrollListNearestFranchises(), GroupLayout.Alignment.LEADING, 0, 518, Short.MAX_VALUE))
				.addContainerGap());
			pack();
			this.setSize(550, 356);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	* This method should return an instance of this class which does 
	* NOT initialize it's GUI elements. This method is ONLY required by
	* Jigloo if the superclass of this class is abstract or non-public. It 
	* is not needed in any other situation.
	 */
	public static Object getGUIBuilderInstance() {
		return new NearestFranchisesView(Boolean.FALSE);
	}
	
	/**
	 * This constructor is used by the getGUIBuilderInstance method to
	 * provide an instance of this class which has not had it's GUI elements
	 * initialized (ie, initGUI is not called in this constructor).
	 */
	private NearestFranchisesView(Boolean initGUI) {
		super();
	}
	
	/**
	 * Updates all the fields with the latest information.
	 */
	private void refreshView() {
		// TODO Auto-generated method stub
		labelFranchiseName.setText(franchise.getName());
		List<Franchise> nearestFranchises = franchise.getNearestFranchises();
		if(!nearestFranchises.isEmpty()) {
			Object[] franchiseArray = nearestFranchises.toArray();
			Arrays.sort(franchiseArray);
			listNearestFranchises.setListData(franchiseArray);
			listNearestFranchises.setEnabled(true);
		}
		else {
			listNearestFranchises.setListData(new String[] {"Nenhuma franquia próxima."});
			listNearestFranchises.setEnabled(false);
		}
	}

	@Override
	public void propertyChanged(FranchiseEvent ev) {
		refreshView();
	}
	
	private JButton getButtonAdd() {
		if(buttonAdd == null) {
			buttonAdd = new JButton();
			buttonAdd.setText("Adicionar conexão");
			buttonAdd.setAction(getActionAdd());
		}
		return buttonAdd;
	}
	
	private JScrollPane getScrollListNearestFranchises() {
		if(scrollListNearestFranchises == null) {
			scrollListNearestFranchises = new JScrollPane();
			scrollListNearestFranchises.setViewportView(getListNearestFranchises());
		}
		return scrollListNearestFranchises;
	}
	
	private JList getListNearestFranchises() {
		if(listNearestFranchises == null) {
			ListModel listNearestFranchisesModel = 
				new DefaultComboBoxModel(
						new String[] { "Nenhuma franquia próxima." });
			listNearestFranchises = new JList();
			listNearestFranchises.setModel(listNearestFranchisesModel);
			listNearestFranchises.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			listNearestFranchises.setEnabled(false);
		}
		return listNearestFranchises;
	}
	
	private AbstractAction getAbstractAction1() {
		if(abstractAction1 == null) {
			abstractAction1 = new AbstractAction("Voltar", null) {
				public void actionPerformed(ActionEvent evt) {
					dispose();
				}
			};
			abstractAction1.putValue(javax.swing.Action.MNEMONIC_KEY, new Integer(java.awt.event.KeyEvent.VK_V));
		}
		return abstractAction1;
	}
	
	@Override
	protected void thisWindowClosed(WindowEvent evt) {
		super.thisWindowClosed(evt);
		franchise.removeFranchiseListener(this);
	}
	
	private AbstractAction getActionAdd() {
		if(actionAdd == null) {
			actionAdd = new AbstractAction("Adicionar conexão", null) {
				public void actionPerformed(ActionEvent evt) {
					Franchise selectedFranchise = SearchFranchiseDialog.showDialog(NearestFranchisesView.this, NearestFranchisesView.this, Data.getInstance().getHeadquarters());
					
					if(selectedFranchise != null) {
						try {
							franchiseController.addNearestFranchise(selectedFranchise);
						}
						catch(FranchiseControllerException e) {
							JOptionPane.showMessageDialog(NearestFranchisesView.this, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
						}
					}
				}
			};
			actionAdd.putValue(javax.swing.Action.MNEMONIC_KEY, new Integer(java.awt.event.KeyEvent.VK_A));
		}
		return actionAdd;
	}
	
	private AbstractAction getActionDelete() {
		if(actionDelete == null) {
			actionDelete = new AbstractAction("Remover conexão", null) {
				public void actionPerformed(ActionEvent evt) {
					Franchise selectedFranchise = (Franchise)listNearestFranchises.getSelectedValue();
					
					if(selectedFranchise == null) {
						JOptionPane.showMessageDialog(NearestFranchisesView.this, "Nenhuma franquia foi selecionada.", "Erro", JOptionPane.ERROR_MESSAGE);
					}						
					else {
						try {
							franchiseController.removeNearestFranchise(selectedFranchise);
						}
						catch(FranchiseControllerException e) {
							JOptionPane.showMessageDialog(NearestFranchisesView.this, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
						}
					}
				}
			};
			actionDelete.putValue(javax.swing.Action.MNEMONIC_KEY, new Integer(java.awt.event.KeyEvent.VK_R));
		}
		return actionDelete;
	}
}
